#!/bin/bash

# Systemd 用户服务管理脚本
# 用于管理 lesson-plan 项目的后端和 MongoDB 服务

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 服务名称
BACKEND_SERVICE="lesson-plan-backend"
MONGODB_SERVICE="mongodb"

# 函数：打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 函数：检查服务状态
check_status() {
    local service=$1
    if systemctl --user is-active --quiet "$service.service"; then
        print_message "$GREEN" "✓ $service 正在运行"
        systemctl --user status "$service.service" --no-pager | head -n 3
    else
        print_message "$RED" "✗ $service 未运行"
    fi
}

# 函数：启动服务
start_service() {
    local service=$1
    print_message "$YELLOW" "启动 $service..."
    systemctl --user start "$service.service"
    sleep 2
    check_status "$service"
}

# 函数：停止服务
stop_service() {
    local service=$1
    print_message "$YELLOW" "停止 $service..."
    systemctl --user stop "$service.service"
    print_message "$GREEN" "$service 已停止"
}

# 函数：重启服务
restart_service() {
    local service=$1
    print_message "$YELLOW" "重启 $service..."
    systemctl --user restart "$service.service"
    sleep 2
    check_status "$service"
}

# 函数：启用服务（开机自启）
enable_service() {
    local service=$1
    print_message "$YELLOW" "启用 $service 开机自启..."
    systemctl --user enable "$service.service"
    print_message "$GREEN" "$service 已设置为开机自启"
}

# 函数：禁用服务（取消开机自启）
disable_service() {
    local service=$1
    print_message "$YELLOW" "禁用 $service 开机自启..."
    systemctl --user disable "$service.service"
    print_message "$GREEN" "$service 已取消开机自启"
}

# 函数：查看日志
view_logs() {
    local service=$1
    print_message "$YELLOW" "显示 $service 最近的日志..."
    journalctl --user -u "$service.service" -n 50 --no-pager
}

# 函数：重新加载 systemd 配置
reload_daemon() {
    print_message "$YELLOW" "重新加载 systemd 用户配置..."
    systemctl --user daemon-reload
    print_message "$GREEN" "配置已重新加载"
}

# 主菜单
show_menu() {
    echo "======================================"
    print_message "$GREEN" "Lesson Plan 服务管理工具"
    echo "======================================"
    echo "1) 查看所有服务状态"
    echo "2) 启动所有服务"
    echo "3) 停止所有服务"
    echo "4) 重启所有服务"
    echo "5) 启动后端服务"
    echo "6) 启动 MongoDB"
    echo "7) 停止后端服务"
    echo "8) 停止 MongoDB"
    echo "9) 查看后端日志"
    echo "10) 查看 MongoDB 日志"
    echo "11) 启用所有服务开机自启"
    echo "12) 禁用所有服务开机自启"
    echo "13) 重新加载配置"
    echo "0) 退出"
    echo "======================================"
}

# 主程序
main() {
    # 确保 MongoDB 数据目录存在
    mkdir -p ~/mongodb/data ~/mongodb/logs
    
    # 如果没有参数，显示菜单
    if [ $# -eq 0 ]; then
        while true; do
            show_menu
            read -p "请选择操作 [0-13]: " choice
            
            case $choice in
                1)
                    check_status "$MONGODB_SERVICE"
                    check_status "$BACKEND_SERVICE"
                    ;;
                2)
                    reload_daemon
                    start_service "$MONGODB_SERVICE"
                    sleep 3
                    start_service "$BACKEND_SERVICE"
                    ;;
                3)
                    stop_service "$BACKEND_SERVICE"
                    stop_service "$MONGODB_SERVICE"
                    ;;
                4)
                    restart_service "$MONGODB_SERVICE"
                    sleep 3
                    restart_service "$BACKEND_SERVICE"
                    ;;
                5)
                    start_service "$BACKEND_SERVICE"
                    ;;
                6)
                    start_service "$MONGODB_SERVICE"
                    ;;
                7)
                    stop_service "$BACKEND_SERVICE"
                    ;;
                8)
                    stop_service "$MONGODB_SERVICE"
                    ;;
                9)
                    view_logs "$BACKEND_SERVICE"
                    ;;
                10)
                    view_logs "$MONGODB_SERVICE"
                    ;;
                11)
                    enable_service "$MONGODB_SERVICE"
                    enable_service "$BACKEND_SERVICE"
                    print_message "$YELLOW" "注意：需要运行 'loginctl enable-linger' 以确保用户服务在未登录时也能运行"
                    ;;
                12)
                    disable_service "$BACKEND_SERVICE"
                    disable_service "$MONGODB_SERVICE"
                    ;;
                13)
                    reload_daemon
                    ;;
                0)
                    print_message "$GREEN" "退出"
                    exit 0
                    ;;
                *)
                    print_message "$RED" "无效的选择"
                    ;;
            esac
            
            echo
            read -p "按 Enter 继续..."
        done
    else
        # 命令行参数模式
        case $1 in
            start)
                reload_daemon
                start_service "$MONGODB_SERVICE"
                sleep 3
                start_service "$BACKEND_SERVICE"
                ;;
            stop)
                stop_service "$BACKEND_SERVICE"
                stop_service "$MONGODB_SERVICE"
                ;;
            restart)
                restart_service "$MONGODB_SERVICE"
                sleep 3
                restart_service "$BACKEND_SERVICE"
                ;;
            status)
                check_status "$MONGODB_SERVICE"
                check_status "$BACKEND_SERVICE"
                ;;
            enable)
                enable_service "$MONGODB_SERVICE"
                enable_service "$BACKEND_SERVICE"
                ;;
            disable)
                disable_service "$BACKEND_SERVICE"
                disable_service "$MONGODB_SERVICE"
                ;;
            reload)
                reload_daemon
                ;;
            *)
                echo "用法: $0 [start|stop|restart|status|enable|disable|reload]"
                echo "或者直接运行 $0 进入交互式菜单"
                exit 1
                ;;
        esac
    fi
}

main "$@"